package com.yunxi.service.dubboService.impl.sto;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yunxi.baseDataToHub.pojo.app.OrderStatusVO;
import com.yunxi.baseDataToHub.service.app.AppDubboService;
import com.yunxi.core.util.DateUtil;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.DictConstant;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.hubToBiz.pojo.HubProduceTracePlanVO;
import com.yunxi.hubToBiz.pojo.HubVehicleMftInfoVO;
import com.yunxi.hubToBiz.service.HubProduceTraceService;
import com.yunxi.model.order.OrderCustomer;
import com.yunxi.model.order.OrderVehicle;
import com.yunxi.model.otd.OtdOrderSo;
import com.yunxi.model.sto.VehicleOffline;
import com.yunxi.service.localService.OrderCustomerService;
import com.yunxi.service.localService.OrderVehicleService;
import com.yunxi.service.localService.otd.OtdOrderSoService;
import com.yunxi.service.localService.sto.StoStockInPlanService;
import com.yunxi.service.localService.sto.VehicleOfflineService;
import com.yunxi.sto.pojo.StoStockInPlanVO;
import com.yunxi.sto.service.StoStockInPlanDubboService;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.annotation.Order;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 车辆下线生成入库计划 服务实现类
 * </p>
 * 状态码（举例）	描述	备注
 * 1100	        进焊装
 * 3000	        出焊装
 * 4000	        进涂装
 * 5000	        出涂装
 * 6000	        进总装
 * 7000	        出总装
 * 8000或9200	收车	不合格为9200
 *
 *
 * 跟踪点（举例）	描述	备注
 * AP21_TP_2100	进焊装	AP21表示工厂代码
 * AP21_TP_2999	出焊装
 * AP21_TP_4100	进涂装
 * AP21_TP_4999	出涂装
 * AP21_TP_6100	进总装
 * AP21_TP_6999	出总装
 * AP21_TP_8000	收车
 *
 * @author caoYong
 * @since 2019-05-28
 */

public class HubProduceTraceServiceImpl implements HubProduceTraceService {

    private static final Logger logger = LoggerFactory.getLogger(HubProduceTraceServiceImpl.class);

    @Autowired
    StoStockInPlanDubboService stoStockInPlanDubboService;

    @Autowired
    @Qualifier("vehicleOfflineServiceImpl")
    VehicleOfflineService carService;

    @Autowired
    @Qualifier(value = "stoStockInPlanServiceImpl")
    StoStockInPlanService stoStockInPlanService;

    @Autowired
    @Qualifier("otdOrderSoServiceImpl")
    OtdOrderSoService soService;

    @Autowired
    @Qualifier("orderCustomerServiceImpl")
    OrderCustomerService orderCustomerService;

    @Autowired
    AppDubboService appDubboService;

    @Autowired
    @Qualifier("orderVehicleServiceImpl")
    OrderVehicleService orderVehicleService;

    /**
     * MES生产跟踪
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult updateCarInfo(List<HubProduceTracePlanVO> list) throws Exception {
        if (!CollectionUtils.isEmpty(list)) {
            for (HubProduceTracePlanVO tracePlanVO : list) {
                Map<String, Object> map = new HashMap<>();
                if (StringUtils.isEmpty(tracePlanVO.getOrdno())) {
                    logger.debug("生产计划号为空");
                    continue;
                }
                //生产计划号
                map.put("sapOrderNo", tracePlanVO.getOrdno());
                //记账日期
                if (!StringUtils.isEmpty(tracePlanVO.getBudat())) {
                    map.put("zpostd", tracePlanVO.getBudat());
                }
                // VIN不为空
                if (!StringUtils.isEmpty(tracePlanVO.getZzvin())) {
                    map.put("vin", tracePlanVO.getZzvin());
                }

                // 进焊装
                switch (tracePlanVO.getStCode()) {
                    case "1100":
                        map.put("actualInWeldingTime", DateUtil.parse(tracePlanVO.getZpassd(), "yyyyMMddHHmmss"));
                        map.put("carState", DictConstant.VEHICLE_TURN_STATE_04HZSX);

                        break;
                    case "3000":
                        // 出焊装
                        map.put("actualOutWeldingTime", DateUtil.parse(tracePlanVO.getZpassd(), "yyyyMMddHHmmss"));
                        map.put("carState", DictConstant.VEHICLE_TURN_STATE_05HZXX);

                        break;
                    case "4000":
                        // 进涂装
                        map.put("actualInPaintTime", DateUtil.parse(tracePlanVO.getZpassd(), "yyyyMMddHHmmss"));
                        map.put("carState", DictConstant.VEHICLE_TURN_STATE_06TZSX);

                        break;
                    case "5000":
                        // 出涂装
                        map.put("actualOutPaintTime", DateUtil.parse(tracePlanVO.getZpassd(), "yyyyMMddHHmmss"));
                        map.put("carState", DictConstant.VEHICLE_TURN_STATE_07TZXX);

                        break;
                    case "5100":
                        // 出涂装
                        map.put("actualOutPaintTime", DateUtil.parse(tracePlanVO.getZpassd(), "yyyyMMddHHmmss"));
                        map.put("carState", DictConstant.VEHICLE_TURN_STATE_07TZXX);

                        break;
                    case "6000":
                        // 进总装
                        map.put("actualInFinalAssemblyTime", DateUtil.parse(tracePlanVO.getZpassd(), "yyyyMMddHHmmss"));
                        map.put("carState", DictConstant.VEHICLE_TURN_STATE_02ZZSX);

                        break;
                    case "7000":
                        // 出总装
                        map.put("actualOutFinalAssemblyTime",
                            DateUtil.parse(tracePlanVO.getZpassd(), "yyyyMMddHHmmss"));
                        map.put("carState", DictConstant.VEHICLE_TURN_STATE_03ZZXX);

                        break;
                    default:
                        if (tracePlanVO.getStCode().equals("8000")) {
                            //合格
                            map.put("isQualified", "1");
                        } else if (tracePlanVO.getStCode().equals("9200")) {
                            // 不合格
                            map.put("isQualified", "0");
                        }
                        map.put("actualOfflineTime", DateUtil.parse(tracePlanVO.getZpassd(), "yyyyMMddHHmmss"));
                        map.put("carState", DictConstant.VEHICLE_TURN_STATE_08CLXX);
                        //生成入库单
//                        addStockInPlan(tracePlanVO);
                        logger.info("车辆下线生成入库单，VIN：" + tracePlanVO.getZzvin());
                        break;
                }
                carService.updateCarTraceInfo(map);
                logger.info("更新车辆信息，Map：" + map);

                /*
                    PMS -> APP
                    跟踪站点
                    20190827
                */
                // 跟踪站点发送APP
                // 查询生产计划
                LambdaQueryWrapper<OtdOrderSo> soQueryWrapper = new LambdaQueryWrapper<>();
                soQueryWrapper.eq(OtdOrderSo::getSapOrderNo, tracePlanVO.getOrdno());
                OtdOrderSo orderSo = soService.getOne(soQueryWrapper);
                if (orderSo == null) {
                    logger.info("未找到生产计划，SAP订单号：" + tracePlanVO.getOrdno());
                    return ResponseUtil.fail(-1, "未找到生产计划，SAP订单号：" + tracePlanVO.getOrdno());
                }
                LambdaQueryWrapper<OrderVehicle> lambdaQueryWrapper = new LambdaQueryWrapper<>();
                lambdaQueryWrapper.eq(OrderVehicle::getZordNo, orderSo.getPlanNo());
                OrderVehicle orderVehicle = orderVehicleService.getOne(lambdaQueryWrapper);
                // 更新批售订单VIN
                if (orderVehicle != null) {
                    if (!StringUtils.isEmpty(tracePlanVO.getZzvin())) {
                        orderVehicle.setVin(tracePlanVO.getZzvin());
                        orderVehicleService.updateById(orderVehicle);
                    }
                    if (!StringUtils.isEmpty(orderVehicle.getCustomOrderNo())) {
                        LambdaQueryWrapper<OrderCustomer> wrapper = new LambdaQueryWrapper<>();
                        wrapper.eq(OrderCustomer::getOrderCustomerNo, orderVehicle.getCustomOrderNo());
                        List<OrderCustomer> orderCustomers = orderCustomerService.list(wrapper);
                        if (!CollectionUtils.isEmpty(orderCustomers)) {
                            orderCustomers.get(0).setVin(tracePlanVO.getZzvin());
                            orderCustomerService.save(orderCustomers.get(0));

                            OrderStatusVO statusVO = new OrderStatusVO();
                            statusVO.setZzvin(tracePlanVO.getZzvin());
                            statusVO.setRpname(tracePlanVO.getRpname());
                            statusVO.setZpassd(tracePlanVO.getZpassd());
                            statusVO.setStCode(tracePlanVO.getStCode());
                            statusVO.setOrderStatus(orderCustomers.get(0).getOrderStatus().toString());
                            statusVO.setOrderNo(orderCustomers.get(0).getOrderCustomerNo());
                            appDubboService.sendOrderStatusPMS2APP(statusVO);
                        }
                    }
                }
            }
            return ResponseUtil.ok("success");
        } else {
            return ResponseUtil.fail(-1, "操作失败,list为空!");
        }


    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult updateCarMftInfo(List<HubVehicleMftInfoVO> list) {
        if (!CollectionUtils.isEmpty(list)) {
            for (HubVehicleMftInfoVO infoVO : list) {
                //查询车辆
                VehicleOffline car = carService.selectCarByVin(infoVO.getVin());
                if (car == null) {
                    logger.info("未找到车辆，VIN：" + infoVO.getVin());
                    return ResponseUtil.fail(-1, "未找到车辆，VIN：" + infoVO.getVin());
                }
                //	电池序列号
                car.setBettaryCode(infoVO.getBatSN());
                //	电机序列号
                car.setMotorCode(infoVO.getMotSN());
                //	电控序列号
                car.setElectronicControl(infoVO.getConSN());
                if (!carService.updateById(car)) {
                    logger.info("更新车辆信息失败，乐观锁冲突!");
                }
            }
        } else {
            logger.info("操作失败,list为空!");
            return ResponseUtil.fail(-1, "操作失败,list为空!");
        }
        return ResponseUtil.ok("success");
    }

    /**
     * 下线生成入库计划
     *
     * @param produceTracePlanVO 车辆生产跟踪VO
     */
    private void addStockInPlan(HubProduceTracePlanVO produceTracePlanVO) throws Exception {
        StoStockInPlanVO stoStockInPlanVO = new StoStockInPlanVO();
        stoStockInPlanVO.setVin(produceTracePlanVO.getZzvin());
        stoStockInPlanVO.setZordNo(produceTracePlanVO.getOrdno());
        stoStockInPlanVO.setStockInType("1");
        stoStockInPlanVO.setBillCreateTime(new Date());
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(date);
        stoStockInPlanVO.setPlanStockInDate(format);
        stoStockInPlanService.saveAndUpdate(stoStockInPlanVO);
    }
}
